<template>
  <div class="admin-request-container">
    <el-card class="header-card" shadow="hover">
      <div class="page-header">
        <div class="title-section">
          <el-icon :size="28" color="#409EFF"><Tickets /></el-icon>
          <h2>诉求管理</h2>
        </div>
        <el-button type="primary" @click="fetchStats">
          <el-icon><Refresh /></el-icon>
          刷新统计
        </el-button>
      </div>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-row">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <el-icon :size="32" color="#409EFF"><Files /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.total || 0 }}</div>
            <div class="stat-label">总诉求数</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card" shadow="hover" @click="filterByStatus('PENDING')">
        <div class="stat-content">
          <el-icon :size="32" color="#909399"><Clock /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.pending || 0 }}</div>
            <div class="stat-label">待处理</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card" shadow="hover" @click="filterByStatus('PROCESSING')">
        <div class="stat-content">
          <el-icon :size="32" color="#E6A23C"><Loading /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.processing || 0 }}</div>
            <div class="stat-label">处理中</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card" shadow="hover" @click="filterByStatus('RESOLVED')">
        <div class="stat-content">
          <el-icon :size="32" color="#67C23A"><Select /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.resolved || 0 }}</div>
            <div class="stat-label">已解决</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card" shadow="hover" @click="filterByStatus('REJECTED')">
        <div class="stat-content">
          <el-icon :size="32" color="#F56C6C"><CloseBold /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.rejected || 0 }}</div>
            <div class="stat-label">已拒绝</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card" shadow="hover" @click="filterByUserType('STUDENT')">
        <div class="stat-content">
          <el-icon :size="32" color="#409EFF"><User /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.studentCount || 0 }}</div>
            <div class="stat-label">学生诉求</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card" shadow="hover" @click="filterByUserType('TEACHER')">
        <div class="stat-content">
          <el-icon :size="32" color="#E6A23C"><Avatar /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.teacherCount || 0 }}</div>
            <div class="stat-label">教师诉求</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 筛选区域 -->
    <el-card class="filter-card" shadow="hover">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" @change="fetchRequests" clearable style="width: 180px">
            <el-option label="全部" value="ALL" />
            <el-option label="待处理" value="PENDING" />
            <el-option label="处理中" value="PROCESSING" />
            <el-option label="已解决" value="RESOLVED" />
            <el-option label="已拒绝" value="REJECTED" />
          </el-select>
        </el-form-item>
        <el-form-item label="提交人类型">
          <el-select v-model="filterForm.userType" placeholder="请选择提交人类型" @change="fetchRequests" clearable style="width: 180px">
            <el-option label="全部" value="ALL" />
            <el-option label="学生" value="STUDENT" />
            <el-option label="教师" value="TEACHER" />
          </el-select>
        </el-form-item>
        <el-form-item label="诉求类型">
          <el-select v-model="filterForm.requestType" placeholder="请选择诉求类型" @change="fetchRequests" clearable style="width: 180px">
            <el-option label="全部" value="ALL" />
            <el-option label="成绩申诉" value="GRADE" />
            <el-option label="选课问题" value="COURSE" />
            <el-option label="课表问题" value="SCHEDULE" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchRequests">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 诉求列表 -->
    <el-card class="table-card" shadow="hover">
      <el-table :data="requestList" v-loading="loading" stripe border style="width: 100%" :row-class-name="tableRowClassName">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="title" label="诉求标题" min-width="180" show-overflow-tooltip />
        <el-table-column prop="userName" label="提交人" width="120" align="center" />
        <el-table-column prop="userType" label="类型" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.userType === 'STUDENT' ? 'primary' : 'warning'">
              {{ scope.row.userType === 'STUDENT' ? '学生' : '教师' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="requestType" label="诉求类型" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getRequestTypeColor(scope.row.requestType)" size="small">
              {{ getRequestTypeName(scope.row.requestType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusColor(scope.row.status)">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="90" align="center">
          <template #default="scope">
            <el-tag :type="getPriorityColor(scope.row.priority)" size="small">
              {{ getPriorityName(scope.row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="submitTime" label="提交时间" width="160" align="center" show-overflow-tooltip />
        <el-table-column prop="adminName" label="处理人" width="100" align="center">
          <template #default="scope">
            {{ scope.row.adminName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewDetail(scope.row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              @click="handleProcess(scope.row)"
              v-if="scope.row.status === 'PENDING' || scope.row.status === 'PROCESSING'"
            >
              <el-icon><Edit /></el-icon>
              处理
            </el-button>
            <el-button 
              type="info" 
              size="small" 
              @click="viewDetail(scope.row)"
              v-else
            >
              <el-icon><View /></el-icon>
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="诉求详情" width="750px">
      <div v-if="currentRequest" class="detail-content">
        <el-descriptions :column="2" border size="large">
          <el-descriptions-item label="诉求标题" :span="2">
            <strong>{{ currentRequest.title }}</strong>
          </el-descriptions-item>
          <el-descriptions-item label="提交人">
            {{ currentRequest.userName }}
          </el-descriptions-item>
          <el-descriptions-item label="提交人类型">
            <el-tag :type="currentRequest.userType === 'STUDENT' ? 'primary' : 'warning'">
              {{ currentRequest.userType === 'STUDENT' ? '学生' : '教师' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="诉求类型">
            <el-tag :type="getRequestTypeColor(currentRequest.requestType)">
              {{ getRequestTypeName(currentRequest.requestType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusColor(currentRequest.status)">
              {{ getStatusName(currentRequest.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityColor(currentRequest.priority)">
              {{ getPriorityName(currentRequest.priority) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="提交时间">{{ currentRequest.submitTime }}</el-descriptions-item>
          <el-descriptions-item label="相关课程" :span="2">
            {{ currentRequest.relatedCourseName || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="详细内容" :span="2">
            <div class="content-box">{{ currentRequest.content }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="处理人" v-if="currentRequest.adminName">
            {{ currentRequest.adminName }}
          </el-descriptions-item>
          <el-descriptions-item label="处理时间" v-if="currentRequest.processTime">
            {{ currentRequest.processTime }}
          </el-descriptions-item>
          <el-descriptions-item label="解决时间" v-if="currentRequest.resolveTime" :span="2">
            {{ currentRequest.resolveTime }}
          </el-descriptions-item>
          <el-descriptions-item label="管理员回复" :span="2" v-if="currentRequest.adminReply">
            <el-alert 
              :title="currentRequest.adminReply" 
              :type="currentRequest.status === 'RESOLVED' ? 'success' : 'error'" 
              :closable="false" 
            />
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button type="primary" @click="showDetailDialog = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 处理诉求对话框 -->
    <el-dialog v-model="showProcessDialog" title="处理诉求" width="650px">
      <div v-if="currentRequest" class="process-content">
        <el-alert 
          :title="`[${currentRequest.userName}] ${currentRequest.title}`" 
          type="info" 
          :closable="false" 
          style="margin-bottom: 20px"
        />
        <div class="request-info">
          <p><strong>诉求内容：</strong></p>
          <div class="content-box">{{ currentRequest.content }}</div>
        </div>
        <el-form :model="processForm" :rules="processRules" ref="processFormRef" label-width="100px">
          <el-form-item label="处理状态" prop="status">
            <el-radio-group v-model="processForm.status">
              <el-radio label="PROCESSING">开始处理</el-radio>
              <el-radio label="RESOLVED">已解决</el-radio>
              <el-radio label="REJECTED">拒绝</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="回复内容" prop="adminReply">
            <el-input 
              v-model="processForm.adminReply" 
              type="textarea" 
              :rows="5" 
              placeholder="请输入回复内容，将发送给提交人" 
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="showProcessDialog = false">取消</el-button>
        <el-button type="primary" @click="submitProcess" :loading="processing">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Tickets, Refresh, Files, Clock, Loading, Select, CloseBold, User, Avatar,
  Search, View, Edit, Delete
} from '@element-plus/icons-vue'
import { getAllRequests, processRequest, getRequestStats } from '../api/request'

// 管理员信息
const user = JSON.parse(localStorage.getItem('user') || '{}')
const adminId = user.adminId || user.admin_id || user.id
const adminName = user.adminName || user.name || '管理员'

// 数据
const loading = ref(false)
const processing = ref(false)
const requestList = ref([])
const stats = ref({})
const showDetailDialog = ref(false)
const showProcessDialog = ref(false)
const currentRequest = ref(null)
const processFormRef = ref(null)

// 筛选表单
const filterForm = reactive({
  status: 'ALL',
  userType: 'ALL',
  requestType: 'ALL'
})

// 处理表单
const processForm = reactive({
  status: 'PROCESSING',
  adminReply: ''
})

// 表单验证规则
const processRules = {
  status: [{ required: true, message: '请选择处理状态', trigger: 'change' }],
  adminReply: [{ required: true, message: '请输入回复内容', trigger: 'blur' }]
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const res = await getRequestStats()
    if (res.code === 200) {
      stats.value = res.data || {}
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取诉求列表
const fetchRequests = async () => {
  try {
    loading.value = true
    const res = await getAllRequests({
      status: filterForm.status === 'ALL' ? null : filterForm.status,
      userType: filterForm.userType === 'ALL' ? null : filterForm.userType,
      requestType: filterForm.requestType === 'ALL' ? null : filterForm.requestType
    })
    
    if (res.code === 200) {
      requestList.value = res.data || []
    } else {
      ElMessage.error(res.message || '获取诉求列表失败')
    }
  } catch (error) {
    console.error('获取诉求列表失败:', error)
    ElMessage.error('获取诉求列表失败')
  } finally {
    loading.value = false
  }
}

// 重置筛选
const resetFilter = () => {
  filterForm.status = 'ALL'
  filterForm.userType = 'ALL'
  filterForm.requestType = 'ALL'
  fetchRequests()
}

// 按状态筛选
const filterByStatus = (status) => {
  filterForm.status = status
  fetchRequests()
}

// 按用户类型筛选
const filterByUserType = (userType) => {
  filterForm.userType = userType
  fetchRequests()
}

// 查看详情
const viewDetail = (row) => {
  currentRequest.value = row
  showDetailDialog.value = true
}

// 处理诉求
const handleProcess = (row) => {
  currentRequest.value = row
  processForm.status = row.status === 'PENDING' ? 'PROCESSING' : row.status
  processForm.adminReply = row.adminReply || ''
  showProcessDialog.value = true
}

// 提交处理
const submitProcess = async () => {
  try {
    await processFormRef.value.validate()
    
    processing.value = true
    const res = await processRequest({
      requestId: currentRequest.value.requestId,
      adminId,
      adminName,
      status: processForm.status,
      adminReply: processForm.adminReply
    })
    
    if (res.code === 200) {
      ElMessage.success('处理成功')
      showProcessDialog.value = false
      fetchRequests()
      fetchStats()
    } else {
      ElMessage.error(res.message || '处理失败')
    }
  } catch (error) {
    if (error !== false) {
      console.error('处理诉求失败:', error)
      ElMessage.error('处理失败')
    }
  } finally {
    processing.value = false
  }
}

// 表格行样式
const tableRowClassName = ({ row }) => {
  if (row.priority === 'URGENT') return 'urgent-row'
  if (row.priority === 'HIGH') return 'high-row'
  return ''
}

// 辅助函数
const getRequestTypeName = (type) => {
  const map = { GRADE: '成绩申诉', COURSE: '选课问题', SCHEDULE: '课表问题', OTHER: '其他' }
  return map[type] || type
}

const getRequestTypeColor = (type) => {
  const map = { GRADE: 'danger', COURSE: 'warning', SCHEDULE: 'primary', OTHER: 'info' }
  return map[type] || 'info'
}

const getStatusName = (status) => {
  const map = { PENDING: '待处理', PROCESSING: '处理中', RESOLVED: '已解决', REJECTED: '已拒绝' }
  return map[status] || status
}

const getStatusColor = (status) => {
  const map = { PENDING: 'info', PROCESSING: 'warning', RESOLVED: 'success', REJECTED: 'danger' }
  return map[status] || 'info'
}

const getPriorityName = (priority) => {
  const map = { LOW: '低', NORMAL: '普通', HIGH: '高', URGENT: '紧急' }
  return map[priority] || priority
}

const getPriorityColor = (priority) => {
  const map = { LOW: 'info', NORMAL: '', HIGH: 'warning', URGENT: 'danger' }
  return map[priority] || ''
}

onMounted(() => {
  fetchStats()
  fetchRequests()
})
</script>

<style scoped>
.admin-request-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-section h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.stats-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 10px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.stat-label {
  font-size: 13px;
  color: #909399;
  margin-top: 5px;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.detail-content, .process-content {
  padding: 10px;
}

.content-box {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  line-height: 1.8;
  color: #606266;
  white-space: pre-wrap;
  word-break: break-word;
}

.request-info {
  margin-bottom: 20px;
}

.request-info p {
  margin-bottom: 10px;
  color: #303133;
}

:deep(.urgent-row) {
  background-color: #fef0f0 !important;
}

:deep(.high-row) {
  background-color: #fdf6ec !important;
}
</style>

